import React, {useEffect} from 'react';
import {ModalHeader, Modal, ModalFooter, Col, Row, ModalBody, CustomInput, Button} from "reactstrap";
import * as Icon from "react-feather"
import {SET_CONTACT_FIELD, SET_CONTACTS_DATA_VALUE, UNSET_CONTACT_FIELD} from "../../../redux/constants/contacts";
import Select from "react-select";
import {connect} from "react-redux";
import {setFieldData, setFieldIdData} from "../../../redux/actions/helper";
import {
  createContact,
  DeleteContact,
  getContact,
  getContacts,
  getTypes,
  UpdateContact
} from "../../../redux/actions/contacts";


const ContactForm = (props) => {
  const {contact, params, reqParams, types} = props
  const {setFieldIdData, setFieldData, getContact, createContact, UpdateContact, DeleteContact} = props

  const Save = () => {
    if (params.contact_id)
      UpdateContact(params.contact_id, contact, reqParams, params)
    else createContact(contact, reqParams, params)
  }

  const Delete = () => {
    if (params.contact_id)
      DeleteContact(params.contact_id, reqParams, params)
  }

  const toggleModal = () => {
    setFieldData(SET_CONTACT_FIELD, 'params', {
      ...params,
      contact_id: null,
      isOpenModal: false
    })
    setFieldData(UNSET_CONTACT_FIELD, '', {})
  }

  const setDataValue = (field, payload, id) => {
    setFieldIdData(SET_CONTACTS_DATA_VALUE, field, payload, id)
  }

  const setContactValue = (payload) => {
    setFieldData(SET_CONTACT_FIELD, 'contact', {...contact, ...payload})
  }

  const renderInput = (id, input) => {
    const boolean = [{value: true, label: 'Да'}, {value: false, label: 'Нет'}];
    switch (input.type) {
      case 'string':
      case 'link':
        return <input
          value={input.value || ''}
          onChange={(e) => setDataValue(input.key, e.target.value, id)}
          className={`contacts-item contacts-input`}/>
      case 'number':
        return <input
          type="number"
          onChange={(e) => setDataValue(input.key, e.target.value, id)}
          value={input.value || ''}
          className={`contacts-item contacts-input`}/>
      case 'boolean':
        return <Select
          className={`contacts-item contacts-input-select`}
          classNamePrefix="dark_select"
          onChange={(e) => setDataValue(input.key, e.value, id)}
          value={{value: input.value || false, label: boolean[input.value === true ? 0 : 1].label}}
          options={boolean}
          isSearchable={false}
          name='typesList'
        />
    }
  }

  const typeChange = (e) => {
    setFieldData(SET_CONTACT_FIELD, 'contact', {
      ...contact,
      data: JSON.parse(e.data),
      type: {
        id: e.value,
        name: e.label,
        data: e.data
      }
    })
  }

  useEffect(() => {
    if (params.isOpenModal)
      if (params.contact_id) {
        getContact(params.contact_id, reqParams, params)
      } else {
        if (types)
          setFieldData(SET_CONTACT_FIELD, 'contact', {
            ...contact,
            data: JSON.parse(types[0].data),
            type: types[0]
          })
      }
  }, [params.isOpenModal])

  return (
    <React.Fragment>
      <Modal
        isOpen={params.isOpenModal}
        toggle={toggleModal}
        size={'lg'}
      >
        <ModalHeader toggle={toggleModal}>
          {params.contact_id ? 'Редактировать контакт' : 'Добавить контакт'} <Icon.UserPlus size={20}/>
        </ModalHeader>
        <ModalBody className={'p-2'}>
          <Row>
            <Col lg={4} className="mt-1 d-flex align-items-center">
              <h5 className={'m-0'}>Имя Фамилия</h5>
            </Col>
            <Col lg={8} className="mt-1">
              <input
                value={contact.name || ''}
                onChange={(e) => setContactValue({name: e.target.value})}
                className={`contacts-item contacts-input ${contact.name ? '' : 'custom-input-invalid'}`}/>
            </Col>
          </Row>
          <Row>
            <Col lg={4} className="mt-1 d-flex align-items-center">
              <h5 className={'m-0'}>Телефон / Мессенджер</h5>
            </Col>
            <Col lg={6} className="mt-1">
              <input
                value={contact.phone || ''}
                onChange={(e) => setContactValue({phone: e.target.value})}
                className={`contacts-item contacts-input ${contact.phone ? '' : 'custom-input-invalid'}`}/>
            </Col>
          </Row>
          <Row>
            <Col lg={4} className="mt-1 d-flex align-items-center">
              <h5 className={'m-0'}>Email</h5>
            </Col>
            <Col lg={6} className="mt-1">
              <input
                value={contact.email || ''}
                onChange={(e) => setContactValue({email: e.target.value})}
                className={`contacts-item contacts-input ${contact.email ? '' : 'custom-input-invalid'}`}/>
            </Col>
          </Row>
          <Row>
            <Col lg={4} className="mt-1 d-flex align-items-center">
              <h5 className={'m-0'}>Тип контакта</h5>
            </Col>
            <Col lg={6} className="mt-1">
              <Select
                className={`contacts-item contacts-input-select`}
                classNamePrefix="dark_select"
                value={{value: contact.type.id, label: contact.type.name, data: contact.type}}
                options={types.map(value => {
                    return {
                      value: value.id,
                      label: value.name,
                      data: value.data
                    }
                  }
                )}
                isDisabled={params.contact_id}
                isSearchable={false}
                onChange={typeChange}
                name='typesList'
              />
            </Col>
          </Row>

          <hr/>

          <h4>Дополнительно</h4>
          <div>
            {
              contact.data.map((value, id) => {
                return <Row key={id}>
                  <Col lg={4} className="mt-1 d-flex align-items-center">
                    <h5 className={'m-0'}>{value.name}</h5>
                  </Col>
                  <Col lg={6} className="mt-1">
                    {renderInput(id, value)}
                  </Col>
                </Row>
              })
            }
          </div>

        </ModalBody>
        <ModalFooter>
          {
            params.contact_id && <Button.Ripple onClick={Delete} color="danger" className="btn-uppercase">
              Удалить
            </Button.Ripple>
          }
          <Button.Ripple color="primary" onClick={Save} className="btn-uppercase">
            Сохранить
          </Button.Ripple>
        </ModalFooter>
      </Modal>
    </React.Fragment>
  )
}

const mapStateToProps = state => ({
  contact: state.contacts.contact,
  params: state.contacts.params,
  types: state.contacts.types,
  reqParams: state.contacts.reqParams
})

export default connect(mapStateToProps, {
  setFieldData, setFieldIdData, getContact, getTypes, getContacts, createContact, UpdateContact, DeleteContact
})(ContactForm);
